package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.dto.UserRegistrationDTO;
import meiyunting.shiwuzhaoling.model.User;
import meiyunting.shiwuzhaoling.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new UserRegistrationDTO());
        return "user/register";
    }

    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") UserRegistrationDTO registrationDTO,
                             BindingResult result,
                             Model model,
                             RedirectAttributes redirectAttributes) {
        System.out.println("接收到注册请求：用户名=" + registrationDTO.getUsername() + 
                         ", 邮箱=" + registrationDTO.getEmail() + 
                         ", 用户名字节长度=" + registrationDTO.getUsername().getBytes().length);
        
        // 输出验证错误信息
        if (result.hasErrors()) {
            result.getAllErrors().forEach(error -> {
                System.out.println("验证错误: " + error.toString());
            });
            return "user/register";
        }
        
        // 验证密码和确认密码是否匹配
        if (!registrationDTO.getPassword().equals(registrationDTO.getConfirmPassword())) {
            model.addAttribute("errorMessage", "两次输入的密码不一致");
            return "user/register";
        }

        try {
            User registeredUser = userService.registerUser(registrationDTO);
            System.out.println("用户注册成功: " + registeredUser.getUsername() + ", ID=" + registeredUser.getId());
            redirectAttributes.addFlashAttribute("successMessage", "注册成功！请登录");
            return "redirect:/login";
        } catch (RuntimeException e) {
            System.out.println("用户注册失败: " + e.getMessage());
            model.addAttribute("errorMessage", e.getMessage());
            return "user/register";
        }
    }

    @GetMapping("/login")
    public String showLoginForm() {
        return "user/login";
    }

    /**
     * 登录状态检查页面
     */
    @GetMapping("/login-status")
    public String loginStatus(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        boolean isAuthenticated = auth != null && auth.isAuthenticated() && 
                                 !auth.getPrincipal().equals("anonymousUser");
        
        model.addAttribute("isAuthenticated", isAuthenticated);
        
        if (isAuthenticated) {
            User currentUser = userService.getCurrentUser();
            model.addAttribute("currentUser", currentUser);
        }
        
        return "user/login-status";
    }
} 